package com.cloud.note.service.impl;

import com.cloud.note.dto.user.ChangePasswordRequest;
import com.cloud.note.dto.user.UpdateProfileRequest;
import com.cloud.note.dto.user.UserProfileResponse;
import com.cloud.note.model.User;
import com.cloud.note.repository.FavoriteRepository;
import com.cloud.note.repository.NoteRepository;
import com.cloud.note.repository.UserRepository;
import com.cloud.note.repository.UserTokenRepository;
import com.cloud.note.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private NoteRepository noteRepository;

    @Autowired
    private FavoriteRepository favoriteRepository;

    @Autowired
    private UserTokenRepository userTokenRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public UserProfileResponse getUserProfile(String userId) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("用户不存在"));

        long noteCount = noteRepository.findByUserIdAndIsTrashedFalse(userId, PageRequest.of(0, 1)).getTotalElements();
        long favoriteCount = favoriteRepository.findFavoriteNotes(userId, PageRequest.of(0, 1)).getTotalElements();

        return UserProfileResponse.builder()
                .userId(user.getId())
                .username(user.getUsername())
                .email(user.getEmail())
                .noteCount(noteCount)
                .favoriteCount(favoriteCount)
                .isPremium(user.isPremium())
                .storageUsed(user.getStorageUsed())
                .storageLimit(user.getStorageLimit())
                .createdAt(user.getCreatedAt())
                .lastLoginAt(user.getLastLoginAt())
                .build();
    }

    @Override
    @Transactional
    public UserProfileResponse updateProfile(String userId, UpdateProfileRequest updateProfileRequest) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("用户不存在"));

        if (updateProfileRequest.getUsername() != null
                && !updateProfileRequest.getUsername().equals(user.getUsername())) {
            // 检查用户名是否已存在
            if (userRepository.existsByUsername(updateProfileRequest.getUsername())) {
                throw new RuntimeException("用户名已存在");
            }
            user.setUsername(updateProfileRequest.getUsername());
        }

        if (updateProfileRequest.getEmail() != null && !updateProfileRequest.getEmail().equals(user.getEmail())) {
            // 检查邮箱是否已存在
            if (userRepository.existsByEmail(updateProfileRequest.getEmail())) {
                throw new RuntimeException("邮箱已存在");
            }
            user.setEmail(updateProfileRequest.getEmail());
        }

        userRepository.save(user);

        return getUserProfile(userId);
    }

    @Override
    @Transactional
    public void changePassword(String userId, ChangePasswordRequest changePasswordRequest) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("用户不存在"));

        // 验证当前密码
        if (!passwordEncoder.matches(changePasswordRequest.getCurrentPassword(), user.getPassword())) {
            throw new RuntimeException("当前密码不正确");
        }

        // 更新密码
        user.setPassword(passwordEncoder.encode(changePasswordRequest.getNewPassword()));
        userRepository.save(user);

        // 清除所有已登录的令牌，强制重新登录
        userTokenRepository.deleteByUserId(userId);
    }
}